package com.by;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class Productor {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.创建连接工厂   创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setVirtualHost("erp");//虚拟主机 默认是 /
        factory.setPort(5672); //连接端口号
        factory.setHost("192.168.203.130");//服务器地址 默认是localhost
        factory.setUsername("admin");
        factory.setPassword("123456");

        //2.创建连接  资源自动释放（连接、信道 关闭）
        try (Connection conn = factory.newConnection(); Channel channel = conn.createChannel()) {

            //3.声明延迟队列
            String q1 = "lazyQueue";
            channel.queueDeclare(q1, false, false, false, null);

            //4.声明延迟交换器
            String ex = "lazyEx";
            channel.exchangeDeclare(ex, BuiltinExchangeType.DIRECT);

            //5.绑定延迟队列与交换器
            channel.queueBind(q1, ex, "lazy");

            //6.正常队列
            String q2 = "normal";
            Map<String, Object> arg = new HashMap<>();
            arg.put("x-dead-letter-exchange", ex);//指明当前队列中产生的死信投递到哪个交换器
            //如果死信交换器与正常交换器绑定队列  路由键不一致时,必须指定死信路由键的名称
            arg.put("x-dead-letter-routing-key", "lazy");
            //通过ttl实现延迟效果
            arg.put("x-message-ttl", 10000);//延迟10s
            channel.queueDeclare(q2, false, false, false, arg);

            //7.正常交换器
            String exname = "normalEx";
            channel.exchangeDeclare(exname, BuiltinExchangeType.DIRECT);
            //8.队列与交换器绑定
            channel.queueBind(q2, exname, "order");

            //发送消息
            channel.basicPublish(exname, "order", null, "dd20240001".getBytes());

            System.out.println("消息发布完毕，服务器已收到");
        }

    }
}